﻿using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using FluentNHibernate.Cfg.Db;
using NHibernate.Dialect;
using NHibernate.Tool.hbm2ddl;
using OpenWaves.ActivityFeed.NHibernate;

namespace OpenWaves.ActivityFeed.UnitTests_NHibernate
{    
    class NHibernateSqlCeSessionFactory: NHibernateSessionFactory
    {
        private string DatabaseName
        {
            get
            {
                var builder = new SqlCeConnectionStringBuilder(this.Configuration.ConnectionString);
                return builder.DataSource;
            }
        }

        public NHibernateSqlCeSessionFactory(INHibernateSessionFactoryConfiguration configuration)
            : base(configuration)
        {
            
        }

        public override global::NHibernate.ISessionFactory CreateSessionFactory()
        {
            var databaseName = this.DatabaseName;
            if (File.Exists(databaseName)) File.Delete(databaseName);
            using (var compactEngine = new SqlCeEngine(this.Configuration.ConnectionString))
            {
                compactEngine.CreateDatabase();
            }        
            return base.CreateSessionFactory();
        }

        protected override IPersistenceConfigurer Configurer
        {
            get
            {
                return
                    MsSqlCeConfiguration.Standard.ShowSql()
                                        .ConnectionString(this.Configuration.ConnectionString)
                                        .Dialect<ActivityFeedMsSqlCe40Dialect>();
            }
        }

        protected override void ExposeConfiguration(global::NHibernate.Cfg.Configuration configuration)
        {
            configuration.AddConstraints();
            new SchemaExport(configuration).Execute(s => Debug.Write(s), true, false);
        }


    }

    class ActivityFeedMsSqlCe40Dialect : MsSqlCe40Dialect
    {
        public override bool SupportsVariableLimit
        {
            get { return true; }
        }
    }
}